package com.fc.campusapplicationsystem.controller;

import com.fc.campusapplicationsystem.model.Area;
import com.fc.campusapplicationsystem.model.Unit;
import com.fc.campusapplicationsystem.service.UnitService;
import com.fc.campusapplicationsystem.util.ResponseOBJ;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 贺哲
 * @2020-02-29 15:34
 */
@RestController
@RequestMapping("/unitController")
public class UnitController {

    @Autowired
    UnitService unitService;

    @GetMapping("/list")
    public ResponseOBJ<List<Unit>> list(@RequestParam("page") Integer page,
                                        @RequestParam("limit") Integer limit,
                                        @RequestParam(value = "key", required = false) String key) {
        ResponseOBJ<List<Unit>> responseOBJ = ResponseOBJ.getInstance();
        try {
            PageHelper.startPage(page, limit);
            List<Unit> units = unitService.list(key);
            PageInfo<Unit> pageInfo = new PageInfo<>(units);
            responseOBJ.setData(units);
            responseOBJ.setCount(pageInfo.getTotal());
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    /**
     * 这个service_name前端要通过ServicemanController查询之后回显出来用下拉框显示
     * 然后让用户管理员选
     * @param unit
     * @return
     */
    @PostMapping("/add")
    public ResponseOBJ<Integer> add(@RequestBody Unit unit) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        try {
            Integer result = unitService.add(unit);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }
}
